<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="100px" :rules="dynamicFormRules">
                <el-form-item label="账号编号" v-show="isEditShow" prop="account_id">
                    <el-input v-model="formData.account_id" disabled placeholder="请输入账号编号" />
                </el-form-item>
                <el-form-item label="应用标识" prop="package_name">
                    <el-input v-model="formData.package_name" placeholder="请输入应用标识" />
                </el-form-item>
                <el-form-item label="应用渠道" prop="channel">
                    <el-select v-model="formData.channel" placeholder="请选择应用渠道">
                        <el-option
                            v-for="item in channelType.dictData.channel || []"
                            :key="item.value"
                            :label="item.name"
                            :value="Number(item.value)"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="百度akey" v-if="formData.channel == 2" prop="akey">
                    <el-input v-model="formData.akey" placeholder="请输入百度akey" />
                </el-form-item>
                <el-form-item label="key" prop="user_account">
                    <el-input v-model="formData.user_account" placeholder="请输入user账号名" />
                </el-form-item>
                <el-form-item label="Secret" prop="butler_account">
                    <el-input v-model="formData.butler_account" placeholder="请输入管家账号名" />
                </el-form-item>
                <el-form-item label="广告主账号" prop="account_number">
                    <el-input v-model="formData.account_number" placeholder="请输入广告主账号" />
                </el-form-item>
                <el-form-item label="账号名称" prop="account_title">
                    <el-input v-model="formData.account_title" placeholder="请输入账号名称" />
                </el-form-item>

                <el-form-item label="主体名称" prop="company_name">
                    <el-input v-model="formData.company_name" placeholder="请输入主体名称" />
                </el-form-item>

                <el-form-item label="数据源id" v-if="formData.channel == 5" prop="data_id">
                    <el-input v-model="formData.data_id" placeholder="请输入数据源id" />
                </el-form-item>

                <el-form-item label="账号状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">无效</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="回传策略配置">
                    <el-tabs v-model="activeName"  @tab-click="handleClick">
                        <el-tab-pane label="激活" name="activate">
                            <el-form-item label="激活百分比" prop="huichuan_rate_activate">
                                <el-input-number v-model="formData.huichuan_rate.huichuan_rate_activate" :min="0" :max="100" />
                            </el-form-item>
                        </el-tab-pane>
                        <el-tab-pane label="付费" name="pay">
                            <el-form-item label="付费百分比" prop="huichuan_rate_pay">
                                <el-input-number v-model="formData.huichuan_rate.huichuan_rate_pay" :min="0" :max="100" />
                            </el-form-item>
                        </el-tab-pane>
                    </el-tabs>
                </el-form-item>

            </el-form>
        </popup>
    </div>
</template>


<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { accountEdit, accountAdd, accountDetail } from '@/api/client/account'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
import { useDictData } from '@/hooks/useDictOptions'
import type { TabsPaneContext } from 'element-plus'

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})

const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
    return mode.value === 'edit' ? '编辑广告账户信息' : '新增广告账户信息'
})
const isEditShow = computed(() => mode.value === 'edit')
const formData = reactive({
    account_id: '',
    channel: 4,
    user_account: '',
    butler_account: '',
    account_number: '',
    account_title: '',
    data_id: '',
    company_name: '',
    status: 1, // 默认设置有效状态
    package_name: '',
    akey: '',
    // 回传策略相关字段
    huichuan_rate: {
        huichuan_rate_activate: 0,  // 激活回传百分比
        huichuan_rate_pay: 0,   // 付费回传百分比
    }

})

interface DictItem {
    value: string | number
    name: string
}

interface ChannelDictData {
    channel: DictItem[]
}

const channelType = useDictData<ChannelDictData>(['channel'])

const activeName = ref('activate')

const handleClick = (tab: TabsPaneContext, event: Event) => {
    console.log(tab, event)
}

const formRules = {
    account_id: [
        {
            required: true,
            message: '请输入账号标识',
            trigger: ['blur']
        }
    ],
    channel: [
        {
            required: true,
            message: '请输入应用渠道',
            trigger: ['blur']
        }
    ],
    user_account: [
        {
            required: false,
            message: '请输入user账号名',
            trigger: ['blur']
        }
    ],
    butler_account: [
        {
            required: false,
            message: '请输入管家账号名',
            trigger: ['blur']
        }
    ],
    account_number: [
        {
            required: true,
            message: '请输入广告主账号',
            trigger: ['blur']
        }
    ],
    account_title: [
        {
            required: true,
            message: '请输入账号名称',
            trigger: ['blur']
        }
    ],
    data_id: [
        {
            required: false,
            message: '请输入数据源id',
            trigger: ['blur']
        }
    ],
    status: [
        {
            required: true,
            message: '请选择账号状态',
            trigger: ['blur']
        }
    ],
    package_name: [
        {
            required: true,
            message: '请输入应用标识',
            trigger: ['blur']
        }
    ],
    huichuan_rate: [
        {
            required: true,
            message: '请输入回传策略比例配置',
            trigger: ['blur']
        }
    ]
}

// 修改为动态规则
const dynamicFormRules = computed(() => {
    const rules = { ...formRules }

    // 在添加模式下，account_id 不需要必填
    if (mode.value === 'add') {
        rules.account_id = [
            {
                required: false,
                message: '请输入账号标识',
                trigger: ['blur']
            }
        ]
    }

    return rules
})

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }
    mode.value === 'edit' ? await accountEdit(data) : await accountAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = (data: Partial<typeof formData>) => {
    Object.keys(formData).forEach((key) => {
        const k = key as keyof typeof formData
        if (data[k] !== undefined && data[k] !== null) {
            formData[k] = data[k]!
        }
    })
}

const getDetail = async (row: Record<string, any>) => {
    const res = await accountDetail({ account_id: row.account_id })
    setFormData(res)
}

const handleClose = () => {
    emit('close')
}


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
